package cn.hinglo.common.interceptors.kit;

import cn.hinglo.common.annotation.JsonBody;
import cn.hinglo.common.interceptors.base.BaseInterceptor;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Parameter;

/**
 * @createTime: 2020/3/13 : 11:46
 * @author: HingLo
 * @description: 测试
 */
public class JsonBodyInterceptor extends BaseInterceptor {
    @Override
    public Class<? extends Annotation> ignoreAnnotation() {
        return null;
    }

    private static final String JSON_TYPE = "application/json";

    @Override
    public void preHandle(HttpServletRequest request, HttpServletResponse response, Invocation inv) {
        Controller controller = inv.getController();
        String contentType = controller.getRequest().getContentType();
        // 判断contentType 是否包含 application/json
        if (StrUtil.isNotBlank(contentType) && contentType.contains(JSON_TYPE)) {
            // 获取参数类型列表
            Class<?>[] parameterTypes = inv.getMethod().getParameterTypes();
            // 获取执行方法的所有参数列表
            Parameter[] parameters = inv.getMethod().getParameters();
            for (int len = parameterTypes.length, i = 0; i < len; i++) {
                JsonBody jsonBody = parameters[i].getAnnotation(JsonBody.class);
                if (jsonBody != null) {
                    try {
                        Object result = JSONUtil.toBean(controller.getRawData(), parameterTypes[i]);
                        inv.setArg(i, result);
                    } catch (Exception e) {
                        throw new RuntimeException(String.format("请求JSON内容转化失败,原因：%s", e.getMessage()));
                    }
                }
            }
        }
        inv.invoke();
    }
}
